﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using ProjetoComperio.BusinessLogicLayer;

namespace ProjetoComperio.ProjectConfiguration
{
    /// <summary>
    /// Executa todo o código necessário para atualização e configuração do database
    /// </summary>
    class Program
    {
        private const string DATABASECONNECTION = "Data Source=.\\SQLEXPRESS;Initial Catalog=ProjetoComperio;Integrated Security=True";

        static void Main(string[] args)
        {
            Console.WriteLine("Iniciando criação do banco de dados");
            ExecuteEFScripts();
            ExecuteAdditionalScripts();
            ExecuteCreateStudentScript();
            Console.WriteLine("Banco de dados criado com sucesso!");
            Console.Read();
        }

        private static void ExecuteCreateStudentScript()
        {
            new StudentBLL().Create(Test.BusinessLogicLayer.StudentBLLTest.CreateFakeStudent(), "usuarioteste", "abcd1234");
            SqlConnection conn = new SqlConnection(DATABASECONNECTION);
            Server server = new Server(new ServerConnection(conn));
            server.ConnectionContext.ExecuteNonQuery("Update [ProjetoComperio].[dbo].[User] set IsLockedOut=0;");
            Console.WriteLine("Executando criação de usuário padrão... ");
        }

        private static void ExecuteAdditionalScripts()
        {
            var additionalSQLPath = new StringBuilder(Directory.GetCurrentDirectory())
                .Replace("ProjetoComperio.ProjectConfiguration\\bin\\Debug", String.Empty)
                .Append("Scripts\\")
                .Append("ScripComplementarDeConfiguracaoDoBD.sql").ToString();

            SqlConnection conn = new SqlConnection(DATABASECONNECTION);
            Server server = new Server(new ServerConnection(conn));
            server.ConnectionContext.ExecuteNonQuery(new FileInfo(additionalSQLPath).OpenText().ReadToEnd());
            Console.WriteLine("Executando Script Adicional... ");
        }

        private static void ExecuteEFScripts()
        {
            Console.WriteLine("Executando DataContextFactory... ");
            DataLayer.Infra.DataContextFactory.CreateDataBase();
        }
    }
}
